package com.xiaopangzi.wsclient;

import okhttp3.*;
import okio.ByteString;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述: WebSocket客户端，代替HTML中的请求实现
 * 由okhttp组件提供
 *
 * @author : sujinchen
 * @date : 2020/9/24
 */
public class MyOkHttpWebSocketClient extends WebSocketListener {
    private Long total = 0L;
    private Long succeed = 0L;
    private Long failed = 0L;

    private Logger logger = LoggerFactory.getLogger(MyOkHttpWebSocketClient.class);


    @Override
    public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosed(webSocket, code, reason);
        logger.info("【okHttp】onClosed>>>关闭状态码：" + code + ",关闭原因：" + reason);
    }

    @Override
    public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
        super.onClosing(webSocket, code, reason);
        logger.info("【okHttp】onClosing>>>关闭状态码：" + code + ",关闭原因：" + reason);

    }

    @Override
    public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
        super.onFailure(webSocket, t, response);
        logger.info("【okHttp】onFailure>>>异常原因：" + t.getMessage() + ",响应内容：" + response);

    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        super.onMessage(webSocket, text);
        logger.info("【okHttp】onMessage>>>接收(文本)消息：" + text );
        String msg = "用户:发送命令:" + total;
        textSucceedRate(text,msg);
    }

    public void textSucceedRate(String origin, String target) {
        if (origin.equals(target)) {
            succeed++;
        } else {
            failed++;
        }
        total++;
        logger.info(toString());
    }

    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
        super.onMessage(webSocket, bytes);
        logger.info("【okHttp】onMessage>>>接收(字节)消息：" + bytes );
    }

    @Override
    public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
        super.onOpen(webSocket, response);
        logger.info("【okHttp】onOpen>>>打开连接响应内容：" + response );

    }
    @Override
    public String toString() {
        return "MyOkHttpWebSocketClient{总请求数："+total
                +" 成功数量："+succeed
                +" 失败数量："+failed
                +"}";
    }
    public static void main(String[] args) {
        OkHttpClient webSocketClient = new OkHttpClient().newBuilder().build();
        Request request = new Request.Builder().url("ws://localhost:8080/myHandler").build();
        WebSocket webSocket1 = webSocketClient.newWebSocket(request, new MyOkHttpWebSocketClient());
        MyOkHttpWebSocketClient.send(webSocket1);
        //仅仅是Client端的关闭，
        webSocket1.close(1000,"手动关闭");
        webSocket1.send("a");
        WebSocket webSocket2 = webSocketClient.newWebSocket(request, new MyOkHttpWebSocketClient());
        MyOkHttpWebSocketClient.send(webSocket2);
        //仅仅是Client端的关闭，
        webSocket2.close(1000,"手动关闭");
        webSocket2.send("b");
    }

    static void send(WebSocket webSocket) {

        for (int i = 0; i < 10000; i++) {
            webSocket.send(i + "");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
